package com.jinkeen.xiaxie.anim

import android.animation.TypeEvaluator
import kotlin.math.abs

class ColorEvalutor : TypeEvaluator<Any> {
    private var mCurrentRed = 0
    private var mCurrentGreen = 0
    private var mCurrentBlue = 0

    /**
     * evaluate()方法当中传入了三个参数，第一个参数fraction非常重要，这个参数用于表示动画的完成度的，我们应该根据它来计算当前动画的值应该是多少，
     * 第二第三个参数分别表示动画的初始值和结束值。那么上述代码的逻辑就比较清晰了，用结束值减去初始值，算出它们之间的差值，然后乘以fraction这个系数，
     * 再加上初始值，那么就得到当前动画的值了
     */
    override fun evaluate(fraction: Float, startValue: Any, endValue: Any): Any {
        var startColor = startValue as String
        var endColor = endValue as String

        var startRed = Integer.parseInt(startColor.substring(1, 3), 16)
        var startGreen = Integer.parseInt(startColor.substring(3, 5), 16)
        var startBlue = Integer.parseInt(startColor.substring(5, 7), 16)

        var endRed = Integer.parseInt(endColor.substring(1, 3), 16)
        var endGreen = Integer.parseInt(endColor.substring(3, 5), 16)
        var endBlue = Integer.parseInt(endColor.substring(5, 7), 16)

        mCurrentRed = startRed
        mCurrentGreen = startGreen
        mCurrentBlue = startBlue


        var redDiff = abs(startRed - endRed)
        var blueDiff = abs(startBlue - endBlue)
        var greenDiff = abs(startGreen - endGreen)
        var colorDiff = redDiff + greenDiff + blueDiff

        if (mCurrentRed != endRed) {
            mCurrentRed = getCurrentColor(fraction, startRed, endRed, colorDiff, 0)
        } else if (mCurrentGreen != endGreen) {
            mCurrentGreen = getCurrentColor(fraction, startGreen, endGreen, colorDiff, redDiff)
        } else if (mCurrentBlue != endBlue) {
            mCurrentBlue =
                getCurrentColor(fraction, startBlue, endBlue, colorDiff, redDiff + blueDiff)
        }
        var currentColor =
            "#" + getHexString(mCurrentRed) + getHexString(mCurrentGreen) + getHexString(
                mCurrentBlue
            )
        return currentColor
    }

    private fun getCurrentColor(
        fraction: Float,
        startColor: Int,
        endColor: Int,
        diff: Int,
        offset: Int
    ): Int {
        var currentColor = 0
        if (startColor > endColor) {
            currentColor = (startColor - (fraction * diff - offset)).toInt()
            if (currentColor < endColor) {
                currentColor = endColor
            }
        } else {
            currentColor = (startColor + (fraction * diff - offset)).toInt()
            if (currentColor < endColor) {
                currentColor = endColor
            }
        }
        return currentColor
    }

    private fun getHexString(value: Int): String {
        var hexString = Integer.toHexString(value)
        if (hexString.length == 1) {
            hexString = "#" + hexString
        }
        return hexString
    }


}